﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using tutors_clus.Models;
using tutors_clus.ViewModel;
using WebMatrix.WebData;
namespace tutors_clus.Controllers
{
    [Authorize(Roles = "Student")]
    public class StudentController : Controller
    {
        //
        // GET: /Student/
        //public StudentController() 
        //{
        tutors_clubContext db = new tutors_clubContext();
        UsersContext user = new UsersContext();
        public ActionResult Index()
        {
            return View();
        }
        //Danh sách các môn chưa học
        public ActionResult Course_No_Registered() 
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            //int list_reg = db.students.Where(m=>m.username_stu == name).Select(m=>m.id_stu).FirstOrDefault();
            var listreg_bystudentid = db.student_course.Where(s => s.id_stu == id).Select(c=>c.id_cou).ToList();
            var list = db.courses.Where(c => c.status_cou == true && !listreg_bystudentid.Contains(c.id_cou)).OrderByDescending(y => y.createdate_cou.Value.Year).ThenByDescending(m => m.createdate_cou.Value.Month).ThenByDescending(d => d.createdate_cou.Value.Day);
                //from c in db.courses where !(from sc in db.student_course where sc.id_stu == list_reg select sc.id_cou).Contains(c.id_cou) select c;
            return View(list);
        }
        //Đang ký môn học
        public ActionResult Register_Course(int id_course) 
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var cou = db.courses.Find(id_course);
            int count = db.student_course.Where(sc=>sc.id_stu ==id && sc.id_cou == id_course).Count();
            student_course stu_cou = new student_course();
            if (ModelState.IsValid)
            {
                if (cou.status_cou == true)
                {
                    if (count < 1)
                    {
                        cou.registered_num = cou.registered_num + 1;
                        db.Entry(cou).State = EntityState.Modified;
                        db.SaveChanges();
                        stu_cou.id_cou = cou.id_cou;
                        stu_cou.id_stu = id;
                        stu_cou.registered_stu = DateTime.Now;
                        db.student_course.Add(stu_cou);
                        db.SaveChanges();
                    }
                }
            }
            return RedirectToAction("Course_No_Registered");
        }
        //Danh mục các môn đã học
        public ActionResult Course_Registered()
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
           // string name = User.Identity.Name;
            //int a = db.students.Where(m => m.username_stu == name).Select(m => m.id_stu).FirstOrDefault();
            var list_reg = from c in db.courses where (from sc in db.student_course where sc.id_stu == id select sc.id_cou).Contains(c.id_cou) select c;
            return PartialView(list_reg);
        }
        public ActionResult Coures_byStudent(int id_course)
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var check = db.student_course.Where(m => m.id_cou == id_course && m.id_stu == id).Count();
            if (check <= 0)
            {
                return RedirectToAction("Index");
            }
            var namecoures_byStudent = db.courses.Where(c => c.id_cou == id_course).FirstOrDefault();
            ViewBag.id_course = id_course;
            return View(namecoures_byStudent);
        }
        public ActionResult Menu_stu_bycou(int id_course)
        {
            var namecoures = db.courses.Where(c => c.id_cou == id_course).First();
            ViewBag.name_course = namecoures.name_cou;    
            ViewBag.id_course = id_course;
            return PartialView(namecoures);
        }
        //public ActionResult Detail_Coures_byStudent(int id_coures) 
        //{
        //    string name = User.Identity.Name;
        //    int a = db.students.Where(m => m.username_stu == name).Select(m => m.id_stu).FirstOrDefault();
        //    return View();
        //}
        public ActionResult Comment_ByCourse(int id_cou) 
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var check = db.student_course.Where(m => m.id_cou == id_cou && m.id_stu==id).Count();
            var comment = db.comments.Where(m => m.id_cou == id_cou && m.parent == 0);
            if (check <= 0 || comment == null)
            {
                return RedirectToAction("Index");
            }
            ViewBag.id_course = id_cou;
            return View(comment);
        }

        //Them chu de binh luan
        public ActionResult Add_com(int id_cou, string contentCom, string titleCom)
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var check = db.student_course.Where(m => m.id_cou == id_cou && m.id_stu == id).Count();
            var comment = db.comments.Where(i => i.id_cou == id_cou && i.parent == 0);
            if (check <= 0 || comment == null)
            {
                return RedirectToAction("Index");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    if (!String.IsNullOrEmpty(contentCom) && !String.IsNullOrEmpty(titleCom))
                    {
                        comment com = new comment();
                        //com.id_com = id_com;
                        com.id_cou = id_cou;
                        com.content_com = contentCom;
                        com.createdate = DateTime.Now;
                        com.title_com = titleCom;
                        com.parent = 0;
                        string[] role = Roles.GetRolesForUser(User.Identity.Name);
                        if (role.Contains("Student"))
                        {
                            com.id_stu = id;
                            com.isrepply = false;
                        }
                        else
                        {
                            com.id_stu = null;
                            com.isrepply = true;
                        }
                        db.comments.Add(com);
                        db.SaveChanges();
                    }
                }
            }
            return RedirectToAction("Comment_ByCourse", new { id_cou = id_cou});
        }

        //chi tiet binh luan theo tung lop
        public ActionResult Detail_Comment_ByCourse(int id_cou,int id_com)
        {
           int id = WebSecurity.GetUserId(User.Identity.Name);
           var check = db.student_course.Where(m => m.id_cou == id_cou && m.id_stu == id).Count();
           var comment = db.comments.Where(i => i.id_com == id_com && i.id_cou == id_cou);
           if (check <= 0 || comment == null )
            {
                return RedirectToAction("Index");
            }
           var detail_com = db.comments.Where(m => m.parent == id_com);
           ViewBag.detail_comment = detail_com;
           ViewBag.count = detail_com.Count();
           return View(comment);
        }
        
        //tra loi binh luan
        public ActionResult Add_detail_com(int id_cou, int id_com, string contentCom) 
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var check = db.student_course.Where(m => m.id_cou == id_cou && m.id_stu == id).Count();
            var comment = db.comments.Where(i => i.id_com == id_com && i.id_cou == id_cou);
            if (check <= 0 || comment == null)
            {
                return RedirectToAction("Index");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    if (!String.IsNullOrEmpty(contentCom))
                    {
                        comment com = new comment();
                        //com.id_com = id_com;
                        com.id_cou = id_cou;
                        com.content_com = contentCom;
                        com.createdate = DateTime.Now;
                        com.title_com = null;
                        com.parent = id_com;
                        string[] role = Roles.GetRolesForUser(User.Identity.Name);
                        if (role.Contains("Student"))
                        {
                            com.id_stu = id;
                            com.isrepply = false;
                        }
                        else
                        {
                            com.id_stu = null;
                            com.isrepply = true;
                        }
                        db.comments.Add(com);
                        db.SaveChanges();
                    }    
                }
            }
            return RedirectToAction("Detail_Comment_ByCourse", new {id_cou=id_cou,id_com=id_com });
        }

        
        public ActionResult Message_ByCourse(int id_cou) 
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var check = db.student_course.Where(m => m.id_cou == id_cou && m.id_stu == id).Count();
            var message = db.messages.Where(m => m.id_cou == id_cou && m.parent ==0 && m.id_stu == id);
            if (check <= 0 || message == null)
            {
                return RedirectToAction("Index");
            }
            ViewBag.id = id_cou;
            return View(message);
        }

        //Them tin nhan moi cho giao vien day lop
        public ActionResult Add_msg(int id_cou, string contentMsg, string titleMsg, IEnumerable<HttpPostedFileBase> fileuploads)
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var check = db.student_course.Where(m => m.id_cou == id_cou && m.id_stu == id).Count();
            var msg = db.messages.Where(i => i.id_cou == id_cou && i.parent == 0);
            if (check <= 0 || msg == null)
            {
                return RedirectToAction("Index");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    if (!String.IsNullOrEmpty(contentMsg) && !String.IsNullOrEmpty(titleMsg))
                    {
                        message msgs = new message();
                        msgs.id_cou = id_cou;
                        msgs.content_mes = contentMsg;
                        msgs.createdate_msg = DateTime.Now;
                        msgs.title_mes = titleMsg;
                        msgs.parent = 0;
                        string[] role = Roles.GetRolesForUser(User.Identity.Name);
                        if (role.Contains("Student"))
                        {
                            msgs.id_stu = id;
                            msgs.isrepply = false;
                        }
                        else
                        {
                            msgs.id_stu = null;
                            msgs.isrepply = true;
                        }
                        db.messages.Add(msgs);
                        db.SaveChanges();
                        int id_msg = msgs.id_mes;
                        
                        var dirName = encrypt(DateTime.Now.ToString());
                        var create_path = Server.MapPath("~/Content/FileUpload_message/" + User.Identity.Name + "/" + dirName);
                        foreach (HttpPostedFileBase fileupload in fileuploads)
                        {
                            if (fileupload != null && fileupload.ContentLength > 0)
                            {
                                var fileName = Path.GetFileName(fileupload.FileName);
                                var directory = new DirectoryInfo(create_path);

                                if (directory.Exists == false)
                                {
                                    directory.Create();
                                }
                                var path = Path.Combine(create_path, fileName);
                                fileupload.SaveAs(path);
                                 file_attach file = new file_attach();
                                 file.name = fileName;
                                 file.source = "/Content/FileUpload_message/" + User.Identity.Name + "/" + dirName + "/" + fileName;
                                 db.file_attach.Add(file);
                                 db.SaveChanges();
                                 int id_att = file.id_att;
                                 message_file msg_file = new message_file();
                                 msg_file.id_mes = id_msg;
                                 msg_file.id_att = id_att;
                                 db.message_file.Add(msg_file);
                                 db.SaveChanges();
                            }
                        }
                    }
                }
                
            }
            return RedirectToAction("Message_ByCourse", new { id_cou = id_cou });
        }


        public ActionResult Detail_Message(int id_cou, int id_msg) 
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var check = db.student_course.Where(m => m.id_cou == id_cou && m.id_stu == id).Count();
            var message = db.messages.Where(m => m.id_cou == id_cou && m.id_mes==id_msg && m.id_stu == id);
            if (check <= 0 || message == null)
            {
                return RedirectToAction("Index");
            }
            ViewBag.id_msg = id_msg;
            var detail_msg= db.messages.Where(m => m.parent == id_msg);
            ViewBag.detail_msg = detail_msg;
            ViewBag.count = detail_msg.Count();
            return View(message);
        }

        //Tra loi tin nhan co dinh kem file
        public ActionResult Reply_msg(int id_cou, int id_msg, string contentMsg, IEnumerable<HttpPostedFileBase> fileuploads)
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var check = db.student_course.Where(m => m.id_cou == id_cou && m.id_stu == id).Count();
            var msg = db.messages.Where(i => i.id_cou == id_cou && i.id_mes == id_msg);
            if (check <= 0 || msg == null)
            {
                return RedirectToAction("Index");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    if (!String.IsNullOrEmpty(contentMsg))
                    {
                        message msgs = new message();
                        msgs.id_cou = id_cou;
                        msgs.content_mes = contentMsg;
                        msgs.createdate_msg = DateTime.Now;
                        msgs.title_mes = null;
                        msgs.parent = id_msg;
                        string[] role = Roles.GetRolesForUser(User.Identity.Name);
                        if (role.Contains("Student"))
                        {
                            msgs.id_stu = id;
                            msgs.isrepply = false;
                        }
                        else
                        {
                            msgs.id_stu = null;
                            msgs.isrepply = true;
                        }
                        db.messages.Add(msgs);
                        db.SaveChanges();
                        int id_msg_reply = msgs.id_mes;
                        var dirName = encrypt(DateTime.Now.ToString());
                        var create_path = Server.MapPath("~/Content/FileUpload_message/" + User.Identity.Name + "/" + dirName);
                        foreach (HttpPostedFileBase fileupload in fileuploads)
                        {
                            if (fileupload != null && fileupload.ContentLength > 0)
                            {
                                var fileName = Path.GetFileName(fileupload.FileName);
                                var directory = new DirectoryInfo(create_path);

                                if (directory.Exists == false)
                                {
                                    directory.Create();
                                }
                                var path = Path.Combine(create_path, fileName);
                                fileupload.SaveAs(path);
                                file_attach file = new file_attach();
                                file.name = fileName;
                                file.source = "/Content/FileUpload_message/" + User.Identity.Name + "/" + dirName + "/" + fileName;
                                db.file_attach.Add(file);
                                db.SaveChanges();
                                int id_att = file.id_att;
                                message_file msg_file = new message_file();
                                msg_file.id_mes = id_msg_reply;
                                msg_file.id_att = id_att;
                                db.message_file.Add(msg_file);
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            return RedirectToAction("Detail_Message", new { id_cou = id_cou, id_msg = id_msg });
        }
        public static string encrypt(string x)
        {
            MD5 md5 = new MD5CryptoServiceProvider();

            //compute hash from the bytes of text
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(x));

            //get hash result after compute it
            byte[] result = md5.Hash;

            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                //change it into 2 hexadecimal digits
                //for each byte
                strBuilder.Append(result[i].ToString("x2"));
            }

            return strBuilder.ToString();
        }
    }

}
